<?php

namespace App\Http\Controllers;

use App\Exceptions\VerifyException;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Validator;

class Controller extends BaseController
{


    /**
     * 获取请求参数 封装验证
     *
     * @param Request $request
     * @param array $paramRule
     * @return Response|array
     *
     * @author gl
     */
    public function validateParam(Request $request, array $rule)
    {

        // 获取业务参数
        $param = $request->all();

        // 参数验证
        $validator = Validator::make($param, $rule);

        // 判断是否通过验证
        if ($validator->fails()) {

            throw new VerifyException($validator->errors()->first(), '40000');
        }

        // 将当前登录用户id加入到参数中
        $param['current_user'] = $request->header('Ghwl-User');
        $param['current_store'] = $request->header('Ghwl-Store') ?? '';

        return ['status' => true, 'result' => $param];
    }

    
    /**
     * 获取请求参数 封装验证
     *
     * @param Request $request
     * @param array $paramRule
     * @return Response|array
     *
     * @author gl
     */
    public function validateParams(Request $request, array $rule)
    {

        // 获取业务参数
        $param = $request->all();

        // 将当前登录用户id加入到参数中
        $param['current_user'] = $request->header('App-User');
        $param['current_space'] = $request->header('App-Space');

        // 参数验证
        $validator = Validator::make($param, $rule);

        // 判断是否通过验证
        if ($validator->fails()) {

            throw new VerifyException($validator->errors()->first());
        }

        return $param;
    }

    /**
     * 操作成功 response返回格式
     * @return JsonResponse
     */
    public function returnResponse($data = '操作成功', $code = 20000): JsonResponse
    {

        return response()->json(['time' => time(), 'code' => $code, 'data' => $data, 'msg' => "success"]);
    }

    /**
     * 操作失败 response返回格式
     * @return JsonResponse
     */
    public function returnErrorResponse($msg = '操作失败', $code = 40000, $data = ''): JsonResponse
    {

        return response()->json(['time' => time(), 'code' => $code, 'data' => $data, 'msg' => $msg]);
    }

    /**
     * 统一根据 res 的 status 判断返回
     * @return JsonResponse
     */
    public function returnRes($res): JsonResponse
    {
        if ($res['status']) {
            return $this->returnResponse($res['data']);
        }
        return $this->returnErrorResponse($res['msg'] ?? $res['data'], $res['code'] ?? 40000);
    }

    /**
     * 统一根据 res 判断返回
     * @return JsonResponse
     */
    public function returnResult($res, $msg = '操作失败', $code = '40000'): JsonResponse
    {
        if ($res) {
            return $this->returnResponse($res);
        }
        return $this->returnErrorResponse($msg, $code, $res);
    }
}
